package org.example.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.mysql.cj.jdbc.AbandonedConnectionCleanupThread;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Description: 连接池的配置
 * @Author:曹震
 * @Date: 2024/11/19 15:51
 */
@Configuration
@PropertySource("classpath:jdbc.properties")
public class DataSourceConfig {
    @Value("${jdbc.url}")
    private String url;
    @Value("${jdbc.user}")
    private String username;
    @Value("${jdbc.driver}")
    private String driver;
    @Value("${jdbc.password}")
    private String password;
    private DruidDataSource druidDataSource;
    @Bean
    public DruidDataSource dataSource(){
        druidDataSource = new DruidDataSource();
        druidDataSource.setUsername(username);
        druidDataSource.setUrl(url);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driver);
        return druidDataSource;

            }
    @PreDestroy
    public void closeDataSource() {
        if (druidDataSource != null) {
            try {
                druidDataSource.close();
                System.out.println("Druid DataSource closed.");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    @PreDestroy
    public void stopAbandonedConnectionCleanupThread() {
        try {
            AbandonedConnectionCleanupThread.checkedShutdown();
            System.out.println("Abandoned connection cleanup thread stopped.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
